<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 实现mergePromise函数，把传进去的数组按顺序先后执行，并且把返回的数据先后放到数组data中。

  const time = (timer) => {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve()
      }, timer)
    })
  }
  const ajax1 = () => time(2000).then(() => {
    console.log(1);
    return 1
  })
  const ajax2 = () => time(1000).then(() => {
    console.log(2);
    return 2
  })
  const ajax3 = () => time(1000).then(() => {
    console.log(3);
    return 3
  })
  // 1
  function mergePromise (arr) {
    // 在这里写代码
    let data = []
    let pro = Promise.resolve()
    arr.forEach(fn => {
      pro = pro.then(fn).then((res)=>{
        data.push(res)
        return data
      })
    });
    return pro
  }
  // 2
  async function mergePromise1 (arr) {
    let data = []
    let i = 0
    while(i<arr.length){
      let res = await arr[i]()
      data.push(res)
      i++
    }
    return data
  }
  
  mergePromise([ajax1, ajax2, ajax3]).then(data => {
    console.log("done");
    console.log(data); // data 为 [1, 2, 3]
  });
  mergePromise1([ajax1, ajax2, ajax3]).then(data => {
    console.log("done");
    console.log(data); // data 为 [1, 2, 3]
  });

// 要求分别输出
// 1
// 2
// 3
// done
// [1, 2, 3]
  </script>
</body>
</html>